package com.primary.utils;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.openxml4j.opc.OPCPackage;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class WordMerger {
    public static void main(String[] args) {
        try {
            //自行替换文件路径
            List<String> list = new ArrayList<>();


            list.add("C:\\Users\\Administrator\\Desktop\\inputfolder\\HW241584-A-1.docx");
            list.add("C:\\Users\\Administrator\\Desktop\\inputfolder\\HW241734-A.docx");
            list.add("C:\\Users\\Administrator\\Desktop\\inputfolder\\WE240031-A.docx");
            list.add("C:\\Users\\Administrator\\Desktop\\inputfolder\\WP240532-A.docx");

            String fileName = "C:\\Users\\Administrator\\Desktop\\outputfile\\mergedFile.docx";
            CustomXWPFDocument destDoc = new CustomXWPFDocument();
            FileOutputStream out = new FileOutputStream(fileName);

            for (String s : list) {
                // 创建段落对象
                XWPFParagraph paragraph = destDoc.createParagraph();
                XWPFRun run = paragraph.createRun();
                run.setText(paragraph.getText());
                run.setBold(true);
                run.setFontSize(20);
                XWPFDocument content = getWordContent(s);
                for (IBodyElement bodyElement : content.getBodyElements()) {
                    boolean hasImage = false;
                    BodyElementType elementType = bodyElement.getElementType();
                    if (elementType == BodyElementType.PARAGRAPH) {
                        //文字
                        XWPFParagraph srcPr = (XWPFParagraph) bodyElement;
                        //复制样式
                        copyStyle(content, destDoc, content.getStyles().getStyle(srcPr.getStyleID()));
                        XWPFParagraph destPr = destDoc.createParagraph();
                        for (XWPFRun srcPrRun : srcPr.getRuns()) {
                            XWPFRun run1 = destPr.createRun();
                            run1.setText(srcPrRun.text());
                            if (srcPrRun.getEmbeddedPictures().size() > 0) {
                                hasImage = true;
                            }
                            for (XWPFPicture pic : srcPrRun.getEmbeddedPictures()) {
                                byte[] img = pic.getPictureData().getData();
                                long cx = pic.getCTPicture().getSpPr().getXfrm().getExt().getCx();
                                long cy = pic.getCTPicture().getSpPr().getXfrm().getExt().getCy();
                                try {
                                    // Working addPicture Code below...
                                    String blipId = destPr.getDocument().addPictureData(new ByteArrayInputStream(img), Document.PICTURE_TYPE_PNG);
                                    destDoc.createPictureCxCy(blipId, destDoc.getNextPicNameNumber(Document.PICTURE_TYPE_PNG), cx, cy);
                                } catch (InvalidFormatException e1) {
                                    e1.printStackTrace();
                                }
                            }
                        }
                        if (hasImage == false) {
                            int pos = destDoc.getParagraphs().size() - 1;
                            destDoc.setParagraph(srcPr, pos);
                        }
                    }else if (elementType == BodyElementType.TABLE) {
                        XWPFTable table = (XWPFTable) bodyElement;
                        destDoc.createTable();
                        int pos = destDoc.getTables().size() - 1;
                        destDoc.setTable(pos, table);
                    }
                }
            }
            destDoc.write(out);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取文档
     *
     * @param filePath
     * @return
     */
    public static XWPFDocument getWordContent(String filePath) {
        File file = new File(filePath);
        try (FileInputStream fis = new FileInputStream(file)) {
            XWPFDocument document = new XWPFDocument(fis);
            return document;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static void copyStyle(XWPFDocument srcDoc, XWPFDocument destDoc, XWPFStyle style) {
        if (destDoc == null || style == null) return;
        if (destDoc.getStyles() == null) {
            destDoc.createStyles();
        }
        List<XWPFStyle> usedStyleList = srcDoc.getStyles().getUsedStyleList(style);
        for (XWPFStyle xwpfStyle : usedStyleList) {
            destDoc.getStyles().addStyle(xwpfStyle);
        }
    }
}